<template>
  <!-- modify by nieyz 2025/5/20 修复弹窗内表格点击事件不触发问题 -->
  <div class="select-dialog" @mousedown.stop>
    <div class="top-search">
      <ty-plm-input
        class="search-input"
        v-model="searchParams.queryConditions.keyword"
        :options="{
          placeholder: $t('basic.placeholder.plsSearchKeyword'),
          clearable: true
        }"
        :suffix-icon="Search"
        @keydown.enter.prevent="searchTable"
        @clear="searchParams.queryConditions.keyword = ''"
      ></ty-plm-input>
      <ty-plm-popover
        v-if="isAdvancedSearch"
        ref="filterPoper"
        :options="{
          trigger: 'manual',
          placement: 'bottom'
        }"
        popper-class="select-object-search-condition"
        :width="600"
      >
        <template #reference>
          <ty-plm-button
            @click="setPopover(true)"
            class="toolbar-right-filter"
            :options="{ type: 'icon', iconClass: 'iconfont icon-gaojichaxun' }"
          ></ty-plm-button>
        </template>
        <!-- modify by caoy 2025/02/26 传递默认类型到高级查询组件 -->
        <search-condition ref="searchConditonRef" :typeOptions="getDefaultTypeOptions" :typeList="getDefaultTypeList" />
        <ty-plm-dialog-footer>
          <template v-for="item in searchBtnOptions" :key="item.title">
            <ty-plm-button v-if="!item.hide" :options="item" @click="searchOperate(item.key)" />
          </template>
        </ty-plm-dialog-footer>
      </ty-plm-popover>
      <ty-plm-button
        class="toolbar-right-refresh"
        @click="refreshTableData"
        :options="{ type: 'icon', iconClass: 'iconfont icon-shuaxin' }"
      ></ty-plm-button>
    </div>
    <!-- <ty-plm-grid
      ref="tableRef"
      :options="gridOptions"
      :columns="columns"
      :data="tableData"
      class="select-dialog-grid"
      @currentChange="({ row }) => setCurRow(row)"
      @cellDblclick="({ row }) => confirmFunc(row)"
    ></ty-plm-grid> -->
    <!-- 树形表格 -->
    <!-- 使用 Element Plus 的 el-table 实现树形表格 -->
    <el-table
      ref="treeTableRef"
      :data="treeData"
      style="width: 100%"
      :row-key="row => row.oid || row.id || row.objectNumber"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @current-change="handleCurrentChange"
      @row-dblclick="handleRowDblclick"
      highlight-current-row
    >     <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <!-- 动态生成列 -->
      <el-table-column
        v-for="col in validColumns"
        :key="col.field"
        :prop="col.field"
        :label="col.title"
        :width="col.title === '编号' ? 200 : col.width" 
        :formatter="getColumnFormatter(col)"
      >
      </el-table-column>
    </el-table>

    <ty-plm-pagination
      v-if="isAdvancedSearch"
      class="select-object-pagination"
      :options="searchParams.pageInfo"
      @page-change="getAdvancedTableData"
    ></ty-plm-pagination>
  </div>
</template>

<script setup>
import basic from '@common/basic'
const  SearchCondition = basic.getExportResource('src/basic/business-modules/advanced-search/views/components/search-condition.vue').default ;
import { Search } from '@element-plus/icons-vue';
import { ref, computed } from 'vue'

defineOptions({
  name: 'SelectObjectContent',
  inheritAttrs: false
});

const props =defineProps(basic.getExportResource('src/basic/components/ty-select-object/composables/select-object-content.js').createProps())

const emit = defineEmits(basic.getExportResource('src/basic/components/ty-select-object/composables/select-object-content.js').createEmits());
const {
  gridOptions,
  searchParams,
  searchBtnOptions,
  isAdvancedSearch,
  columns,
  tableData,
  filterPoper,
  searchConditonRef,
  tableRef,
  setCurRow,
  setPopover,
  searchTable,
  getAdvancedTableData,
  getTableData,
  searchOperate,

  getDefaultTypeList,
  getDefaultTypeOptions,
  refreshTableData
} = (basic.getExportResource('src/basic/components/ty-select-object/composables/select-object-content.js').useOverride || basic.getExportResource('src/basic/components/ty-select-object/composables/select-object-content.js').useSelectObjectContent)(props, emit);

// 树形表格数据源 - 使用 tableData 作为基础数据
const treeData = computed(() => {
  return gridOptions.data || [];
});
const treeTableRef = ref(null)

// 子组件内部的 confirmFunc
const confirmFunc = () => {
  const selected = treeTableRef.value?.getSelectionRows() || []
  console.log('✅ 子组件选中行:', selected)
  emit('confirm', selected)
}

// 暴露给父组件调用的方法
const getSelectedRows = () => {
  return treeTableRef.value?.getSelectionRows() || []
}

const triggerConfirm = () => {
  confirmFunc() // 主动触发确认
}



// 过滤有效的列配置
const validColumns = computed(() => {
  return (columns.value || []).filter(col => {
    return col && 
           col.field && 
           typeof col.field === 'string' && 
           col.field.trim() !== '';
  });
});

// 获取列格式化函数
const getColumnFormatter = (col) => {
  // 增强参数验证
  if (!col || !col.field || !col.formatter) {
    return null;
  }
  
  // 确保 formatter 是一个函数
  if (typeof col.formatter !== 'function') {
    return null;
  }
  
  // 适配 Element Plus 的 formatter 函数签名
  // Element Plus: (row, column, cellValue, index)
  // 原 formatter 可能期望不同的参数格式
  return (row, column, cellValue, index) => {
    try {
      // 尝试调用原始 formatter，传入适当的参数
      return col.formatter(cellValue, row, index);
    } catch (error) {
      console.warn('Column formatter error:', error);
      return cellValue;
    }
  };
};

// 树形表格事件处理
const handleCurrentChange = (currentRow) => {
  setCurRow(currentRow);
};

const handleRowDblclick = (row) => {
  confirmFunc(row);
};

defineExpose({
  getTableData,
  confirmFunc,
   getSelectedRows,
  triggerConfirm,
 
});

// 暴露方法

setTimeout(() => {
    console.log('第一条数据完整结构:', JSON.stringify(gridOptions.data[0], null, 2));
        console.log('第一条columns:', columns);
}, 10000);
</script>
<style lang="scss">
.select-object-popover.el-popover.el-popper {
  padding: 0;
}
.select-object {
  min-height: 30px;
  width: 100%;
  .tox.tox-tinymce {
    box-sizing: content-box;
  }
}
.select-object-dialog {
  .top-search {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 12px;
    .search-input {
      width: 160px;
      margin-right: 8px;
    }
  }
  .select-object-pagination {
    margin-top: 12px;
    .ty-base-pagination--select {
      overflow: hidden;
    }
  }
}

.select-object-search-condition .base-Dialog-FootBtn {
  padding: 12px 0 0 0;
}
/* 统一取消树形缩进：所有行（包括父节点）都左对齐 */
.select-object-dialog :deep(.el-table__indent) { width: 0 !important; }
.select-object-dialog :deep(.el-table__placeholder) { width: 0 !important; }

/* 第一列保持默认内边距，避免看起来过于贴边，可按需微调 */
.select-object-dialog :deep(.el-table__row > .el-table__cell:first-child) {
  padding-left: 12px !important;
}

/* 展开图标与文本的间距统一 */
.select-object-dialog :deep(.el-table__expand-icon) {
  margin-left: 0 !important;
  margin-right: 4px !important;
}
// ::v-deep .el-table__placeholder {
//   text-indent: 0 !important;
// }
</style>
